﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using External.APICalling;
using BusinessRule.DTO;
using System.Configuration;
using System.Xml;
using MES.DataGateway.DBUtility;
using System.Data;
using log4net;
using System.Data.OracleClient;
using System.Text;
using System.Collections;

namespace SendIndustrialNetwork
{
    public class ERPSendMESDataMethod
    {

        public string GetCDataItem(string source, string strIndex)
        {
            int startIndex = source.IndexOf(string.Format("<{0}>", strIndex)) + strIndex.Length + 2;
            int endIndex = source.IndexOf(string.Format("</{0}>", strIndex));
            return source.Substring(startIndex, endIndex - startIndex);
        }

        public string SaveMfgorder(Dictionary<string, string> strList, DataTable dtAttribute, string remoteServicer)
        {
            #region 机匣测试服务器写入 add:Wangjh 20170925
            CamstarClientAPI clientData;
            if (remoteServicer != null)
            {
                string[] tempStr = remoteServicer.Split('$');
                clientData = new CamstarClientAPI(tempStr[1].ToString(), tempStr[2].ToString(),
                tempStr[0].ToString().Split(':').First(), tempStr[0].ToString().Split(':').Last());
            }
            else
            {

                clientData = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(),
               ConfigurationManager.AppSettings["CamstarPassword"].ToString(), ConfigurationManager.AppSettings["ServerHost"].ToString(), ConfigurationManager.AppSettings["ServerPort"].ToString());
            }
            #endregion
            string resultInfo = string.Empty;
            bool result = false;
            List<ClientAPIEntity> dataList = new List<ClientAPIEntity>();

            CheckOrderType(strList, clientData, ref resultInfo, ref result, dataList);
            CheckProductFamily(strList, clientData);//订单型别--新增逻辑---add by longb 2024-03-06
            if (result)
            {
                FillMfgOrder(strList, dataList);

                Dictionary<string, List<ClientAPIEntity>> m_ChildList = FillAttributes(dtAttribute);

                int count = 0;

                Boolean temBool;
                if (remoteServicer != null)
                {
                    temBool = MfgOrderExist(strList["mfgordername"], ref count, true);
                }
                else
                {
                    temBool = MfgOrderExist(strList["mfgordername"], ref count, false);
                }

                if (temBool)
                    result = clientData.UpdateModelHasSubentityList("MfgOrderMaintDoc", "MfgOrderMaint", strList["mfgordername"], "", "NDO", dataList, "Attributes", m_ChildList, count, ref resultInfo);
                else
                    result = clientData.CreateModelHasSubentityList("MfgOrderMaintDoc", "MfgOrderMaint", "new", dataList, "Attributes", m_ChildList, ref resultInfo);
                if (result)
                    return m_strSuccess;

                else
                    return resultInfo;
            }
            else
                return resultInfo;

        }

        #region product处理

        /// <summary>
        /// 从物料数据中心取值
        /// add:Wangjh 20220401
        /// </summary>
        /// <param name="materialCode"></param>
        /// <returns></returns>
        public DataTable GetJBSTData(string materialCode)
        {
            string strSql = " SELECT jt.*  FROM jbst_sync_mes jt WHERE 1=1 ";
            if (!string.IsNullOrWhiteSpace(materialCode))
            {
                strSql += string.Format(" and jt.t_code='{0}' ", materialCode);
            }
            return OracleHelper.Query(strSql).Tables[0];
        }
        //复制件号
        public Boolean CopyProduct(Dictionary<string, string> strList, ref string strInfo)
        {

            CamstarClientAPI clientData = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(),
              ConfigurationManager.AppSettings["CamstarPassword"].ToString(), ConfigurationManager.AppSettings["ServerHost"].ToString(), ConfigurationManager.AppSettings["ServerPort"].ToString());

            List<ClientAPIEntity> dataEntityList = new List<ClientAPIEntity>();
            ClientAPIEntity dataEntity;

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Name";
            dataEntity.ClientDataValue = strList["productName"];
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Revision";
            dataEntity.ClientDataValue = strList["Revision"];
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "ProductType";
            dataEntity.ClientDataValue = strList["ProductType"];
            dataEntityList.Add(dataEntity);

            if (strList.ContainsKey("MaterialCode") && !string.IsNullOrWhiteSpace(strList["MaterialCode"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "MaterialCode";
                dataEntity.ClientDataValue = strList["MaterialCode"];
                dataEntityList.Add(dataEntity);
            }

            Boolean result = clientData.SaveAsModel("ProductMaint", strList["PdmProductName"], strList["Revision"], dataEntityList, ref strInfo);

            return result;

        }
        //更新件号
        public Boolean UpdateProductByProduct(Dictionary<string, string> strList, DataTable productDt, ref string strInfo)
        {
            CamstarClientAPI clientData = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(),
                ConfigurationManager.AppSettings["CamstarPassword"].ToString(), ConfigurationManager.AppSettings["ServerHost"].ToString(), ConfigurationManager.AppSettings["ServerPort"].ToString());

            List<ClientAPIEntity> dataEntityList = new List<ClientAPIEntity>();

            Dictionary<string, List<ClientAPIEntity>> m_ChildList = new Dictionary<string, List<ClientAPIEntity>>();

            ClientAPIEntity dataEntity;

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.RevisionedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Workflow";
            dataEntity.ClientDataValue = productDt.Rows[0]["workflowname"].ToString();
            dataEntity.ClientDataVersion = productDt.Rows[0]["workflowrevision"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "documentset";
            dataEntity.ClientDataValue = productDt.Rows[0]["documentsetname"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "charactertype";
            dataEntity.ClientDataValue = productDt.Rows[0]["charactertype"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialcode";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialcode"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialname";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialname"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialrequest";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialrequest"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialsize";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialsize"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialspecification";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialspecification"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialtrademark";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialtrademark"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialstatus";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialstatus"].ToString();
            dataEntityList.Add(dataEntity);


            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "workflowroute";
            dataEntity.ClientDataValue = productDt.Rows[0]["workflowroute"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialtype";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialtypename"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "ProductType";
            dataEntity.ClientDataValue = strList["ProductType"];
            dataEntityList.Add(dataEntity);

            if (productDt.Columns.Contains("FirstUsedProduct"))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "FirstUsedProduct";
                dataEntity.ClientDataValue = productDt.Rows[0]["FirstUsedProduct"].ToString();
                dataEntityList.Add(dataEntity);
            }

            if (productDt.Columns.Contains("istopgz"))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "istopgz";
                dataEntity.ClientDataValue = productDt.Rows[0]["istopgz"].ToString();
                dataEntityList.Add(dataEntity);
            }

            string attributeSql = string.Format("select ut.userattributename name,ut.attributevalue from userattribute ut where ut.parentid='{0}'", productDt.Rows[0]["productid"].ToString());
            DataTable attributeDt = OracleHelper.Query(attributeSql).Tables[0];
            m_ChildList = FillAttributes(attributeDt);

            attributeSql = string.Format("select ut.userattributename name,ut.attributevalue from userattribute ut where ut.parentid='{0}'", strList["ProductID"]);//组别件号的属性
            DataTable attributeDt2 = OracleHelper.Query(attributeSql).Tables[0];

            return clientData.UpdateModelHasSubentityList("ProductMaintDoc", "ProductMaint", strList["productName"], strList["Revision"], "RO", dataEntityList, "Attributes", m_ChildList, attributeDt2.Rows.Count, ref strInfo);


        }
        //创建新版本件号
        public Boolean CreateNewRevisionProduct(Dictionary<string, string> strList, string oldRev, DataTable productDt, ref string strInfo)
        {
            CamstarClientAPI clientData = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(),
               ConfigurationManager.AppSettings["CamstarPassword"].ToString(), ConfigurationManager.AppSettings["ServerHost"].ToString(), ConfigurationManager.AppSettings["ServerPort"].ToString());

            List<ClientAPIEntity> dataEntityList = new List<ClientAPIEntity>();

            Dictionary<string, List<ClientAPIEntity>> m_ChildList = new Dictionary<string, List<ClientAPIEntity>>();

            ClientAPIEntity dataEntity;

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Name";
            dataEntity.ClientDataValue = strList["productName"];
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Revision";
            dataEntity.ClientDataValue = strList["Revision"];
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Description";
            dataEntity.ClientDataValue = productDt.Rows[0]["Description"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.RevisionedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Workflow";
            dataEntity.ClientDataValue = productDt.Rows[0]["workflowname"].ToString();
            dataEntity.ClientDataVersion = productDt.Rows[0]["workflowrevision"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "documentset";
            dataEntity.ClientDataValue = productDt.Rows[0]["documentsetname"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "charactertype";
            dataEntity.ClientDataValue = productDt.Rows[0]["charactertype"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialcode";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialcode"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialname";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialname"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialrequest";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialrequest"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialsize";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialsize"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialspecification";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialspecification"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialtrademark";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialtrademark"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialstatus";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialstatus"].ToString();
            dataEntityList.Add(dataEntity);


            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "workflowroute";
            dataEntity.ClientDataValue = productDt.Rows[0]["workflowroute"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "materialtype";
            dataEntity.ClientDataValue = productDt.Rows[0]["materialtypename"].ToString();
            dataEntityList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "ProductType";
            dataEntity.ClientDataValue = strList["ProductType"];
            dataEntityList.Add(dataEntity);

            if (productDt.Columns.Contains("FirstUsedProduct"))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "FirstUsedProduct";
                dataEntity.ClientDataValue = productDt.Rows[0]["FirstUsedProduct"].ToString();
                dataEntityList.Add(dataEntity);
            }

            if (productDt.Columns.Contains("istopgz"))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "istopgz";
                dataEntity.ClientDataValue = productDt.Rows[0]["istopgz"].ToString();
                dataEntityList.Add(dataEntity);
            }

            string attributeSql = string.Format("select ut.userattributename name,ut.attributevalue from userattribute ut where ut.parentid='{0}'", productDt.Rows[0]["ProductID"].ToString());//源件号的属性
            DataTable attributeDt2 = OracleHelper.Query(attributeSql).Tables[0];

            //追加属性

            for (int i = 0; i < attributeDt2.Rows.Count; i++)
            {
                List<ClientAPIEntity> AttributesItem = new List<ClientAPIEntity>();
                AttributesItem.Add(new ClientAPIEntity("Name", DataTypeEnum.DataField, attributeDt2.Rows[i]["name"].ToString(), ""));
                AttributesItem.Add(new ClientAPIEntity("AttributeValue", DataTypeEnum.DataField, attributeDt2.Rows[i]["attributevalue"].ToString(), ""));
                AttributesItem.Add(new ClientAPIEntity("IsExpression", DataTypeEnum.DataField, "False", ""));
                AttributesItem.Add(new ClientAPIEntity("DataType", DataTypeEnum.DataField, 4, ""));
                m_ChildList.Add(i.ToString(), AttributesItem);
            }



            Dictionary<string, Dictionary<string, List<ClientAPIEntity>>> p_mChildList = new Dictionary<string, Dictionary<string, List<ClientAPIEntity>>>();
            p_mChildList.Add("Attributes", m_ChildList);


            return clientData.CreateNewModelRevision("ProductMaint", strList["productName"], oldRev, dataEntityList, p_mChildList, ref strInfo);
        }

        /// <summary>
        /// erp推送的为物料号,此方法处理复制一份product的情况（可能是组别件，叶片锻件，工装件的情况）
        /// </summary>
        /// <param name="pdmProductName"></param>
        /// <param name="para"></param>
        /// <returns></returns>
        public string CopyOrUpdateProductByProduct(string pdmProductName, Dictionary<string, string> para)
        {

            string strMsg = "";
            string productName = para["productName"];//需要处理的件号

            para["Revision"] = GetProductDefaultRev(pdmProductName);//查询pdm件号的默认版本
            if (string.IsNullOrWhiteSpace(para["Revision"]))
            {
                return "件号:" + pdmProductName + "不存在";
            }

            DataTable productDt = GetProductByNameAndRev(productName, "");//推送物料的信息

            if (productDt.Rows.Count == 0)
            {
                if (!CopyProduct(para, ref strMsg))
                {
                    return strMsg;
                }
            }
            else if (productDt.Select(" productrevision='" + para["Revision"] + "'").Length > 0)
            {
                para["ProductID"] = productDt.Rows[0]["ProductID"].ToString();

                DataTable pdmProductDt = GetProductByNameAndRev(pdmProductName, para["Revision"]);

                if (para.ContainsKey("MaterialCode") && !string.IsNullOrWhiteSpace(para["MaterialCode"]))//传入的属性
                {
                    pdmProductDt.Rows[0]["MaterialCode"] = para["MaterialCode"];
                }

                //更新信息
                if (!UpdateProductByProduct(para, pdmProductDt, ref strMsg))
                {
                    return strMsg;
                }
            }
            else//创建版本对象
            {
                DataTable pdmProductDt = GetProductByNameAndRev(pdmProductName, para["Revision"]);
                if (para.ContainsKey("MaterialCode") && !string.IsNullOrWhiteSpace(para["MaterialCode"]))//传入的属性
                {
                    pdmProductDt.Rows[0]["MaterialCode"] = para["MaterialCode"];
                }

                //创建新版本
                if (!CreateNewRevisionProduct(para, productDt.Rows[0]["productrevision"].ToString(), pdmProductDt, ref strMsg))
                {
                    return strMsg;
                }
            }


            //更新productworkflowmapping
            DataTable newProductDt = GetProductByNameAndRev(productName, para["Revision"]);
            if (newProductDt.Rows.Count > 0)
            {
                string pwSql = "SELECT * FROM  productworkflowmapping pw WHERE pw.productid='{0}' AND pw.workflowid='{1}'";

                if (OracleHelper.Query(string.Format(pwSql, newProductDt.Rows[0]["productid"].ToString(), newProductDt.Rows[0]["workflowid"].ToString())).Tables[0].Rows.Count == 0)
                {
                    pwSql = "INSERT INTO productworkflowmapping pw (pw.productid,pw.workflowid) VALUES('{0}','{1}')";

                    OracleHelper.ExecuteSql(string.Format(pwSql, newProductDt.Rows[0]["productid"].ToString(), newProductDt.Rows[0]["workflowid"].ToString()));
                }
            }
            //

            //继承源件号子件号信息
            ineritSubProductInfo(pdmProductName, productName, para["Revision"]);
            //


            return "";

        }
        #endregion


        private static void FillMfgOrder(Dictionary<string, string> strList, List<ClientAPIEntity> dataList)
        {
            ClientAPIEntity dataEntity;
            #region 生产订单
            dataList.Clear();
            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Name";
            dataEntity.ClientDataValue = strList["mfgordername"];
            dataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "OrderType";
            dataEntity.ClientDataValue = strList["OrderType"];
            dataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Factory";
            dataEntity.ClientDataValue = strList["Factory"];
            dataList.Add(dataEntity);

            if (strList.ContainsKey("OrderStatus") && !string.IsNullOrWhiteSpace(strList["OrderStatus"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "OrderStatus";
                dataEntity.ClientDataValue = strList["OrderStatus"];
                dataList.Add(dataEntity);
            }

            if (!string.IsNullOrWhiteSpace(strList["productName"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.RevisionedObjectField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "Product";
                dataEntity.ClientDataValue = strList["productName"];
                dataEntity.ClientDataIsROR = true;
                dataList.Add(dataEntity);
            }

            if (strList.ContainsKey("ProductFamilyName") && !string.IsNullOrWhiteSpace(strList["ProductFamilyName"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "ProductFamilyName";
                dataEntity.ClientDataValue = strList["ProductFamilyName"];
                dataEntity.ClientDataIsROR = true;
                dataList.Add(dataEntity);
            }

            if (strList.ContainsKey("WorkcenterName") && !string.IsNullOrWhiteSpace(strList["WorkcenterName"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "WorkcenterName";
                dataEntity.ClientDataValue = strList["WorkcenterName"];
                dataEntity.ClientDataIsROR = true;
                dataList.Add(dataEntity);
            }

            if (strList.ContainsKey("MRPArea") && !string.IsNullOrWhiteSpace(strList["MRPArea"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "MRPArea";
                dataEntity.ClientDataValue = strList["MRPArea"];
                dataEntity.ClientDataIsROR = true;
                dataList.Add(dataEntity);
            }

            if (strList.ContainsKey("Priority") && !string.IsNullOrWhiteSpace(strList["Priority"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
                dataEntity.ClientDataName = "Priority";
                dataEntity.ClientDataValue = strList["Priority"];
                dataEntity.ClientDataIsROR = true;
                dataList.Add(dataEntity);
            }

            if (strList.ContainsKey("ZZJHY") && !string.IsNullOrWhiteSpace(strList["ZZJHY"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "ZZJHY";
                dataEntity.ClientDataValue = strList["ZZJHY"];
                dataEntity.ClientDataIsROR = true;
                dataList.Add(dataEntity);
            }

            if (strList.ContainsKey("SERNR") && !string.IsNullOrWhiteSpace(strList["SERNR"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "SERNR";
                dataEntity.ClientDataValue = strList["SERNR"];
                dataEntity.ClientDataIsROR = true;
                dataList.Add(dataEntity);
            }

            if (strList.ContainsKey("ZSFJJ") && !string.IsNullOrWhiteSpace(strList["ZSFJJ"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "ZSFJJ";
                dataEntity.ClientDataValue = strList["ZSFJJ"];
                dataEntity.ClientDataIsROR = true;
                dataList.Add(dataEntity);
            }

            if (strList.ContainsKey("IsCompProduct") && !string.IsNullOrWhiteSpace(strList["IsCompProduct"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "IsCompProduct";
                dataEntity.ClientDataValue = strList["IsCompProduct"];
                dataList.Add(dataEntity);
            }
            //合并机型 add by longb 2025-05-27
            if (strList.ContainsKey("ZHBMODEL") && !string.IsNullOrWhiteSpace(strList["ZHBMODEL"]))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "ZHBMODEL";
                dataEntity.ClientDataValue = strList["ZHBMODEL"];
                dataList.Add(dataEntity);
            }

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Qty";
            dataEntity.ClientDataValue = strList["qty"];
            dataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "PlannedStartDate";
            string strTmpYear = strList["PlannedStartDate"].ToString().Substring(0, 4);
            string strTmpMonth = strList["PlannedStartDate"].ToString().Substring(4, 2);
            string strTmpDay = strList["PlannedStartDate"].ToString().Substring(6, 2);
            dataEntity.ClientDataValue = new DateTime(Convert.ToInt32(strTmpYear), Convert.ToInt32(strTmpMonth),
                                                      Convert.ToInt32(strTmpDay)).ToString("yyyy-MM-ddTHH:mm:ss");
            dataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "PlannedCompletionDate";
            strTmpYear = strList["PlannedCompletionDate"].ToString().Substring(0, 4);
            strTmpMonth = strList["PlannedCompletionDate"].ToString().Substring(4, 2);
            strTmpDay = strList["PlannedCompletionDate"].ToString().Substring(6, 2);
            dataEntity.ClientDataValue = new DateTime(Convert.ToInt32(strTmpYear), Convert.ToInt32(strTmpMonth),
                                                      Convert.ToInt32(strTmpDay)).ToString("yyyy-MM-ddTHH:mm:ss");

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "ReceiveDate";
            dataEntity.ClientDataValue = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");


            dataList.Add(dataEntity);
            #endregion
        }

        public string GetProductDefaultRev(string name)
        {
            string strSql = string.Format("SELECT p.productrevision FROM productbase pb " +
                                        "LEFT JOIN product p ON p.productid=pb.revofrcdid " +
                                        " where pb.productname='{0}'", name);
            DataTable dt = OracleHelper.Query(strSql).Tables[0];
            if (dt == null || dt.Rows.Count == 0)
            {
                return "";
            }
            return dt.Rows[0]["productrevision"].ToString();

        }

        public DataTable GetProductByNameAndRev(string name, string rev)
        {
            string strSql = string.Format(@"select p.productid,ds.documentsetname,mt.materialtypename,w.workflowrevision,wb.workflowname,pt.producttypename,pb.*,p.* from product p
            left join productbase pb on pb.productbaseid=p.productbaseid
            left join documentset ds on ds.documentsetid=p.documentsetid
            left join workflow w on w.workflowid=p.workflowid
            left join workflowbase wb on wb.workflowbaseid=w.workflowbaseid
            left join materialtype mt on mt.materialtypeid=p.materialtypeid
             left join producttype pt on pt.producttypeid=p.producttypeid
                        where pb.productname='{0}' ", name);
            if (!string.IsNullOrWhiteSpace(rev))
            {
                strSql += string.Format(" and p.productrevision='{0}' ", rev);
            }

            strSql += " order by p.productid desc ";
            DataTable dt = OracleHelper.Query(strSql).Tables[0];

            return dt;
        }

        private static void CheckOrderType(Dictionary<string, string> strList, CamstarClientAPI clientData, ref string resultInfo, ref bool result, List<ClientAPIEntity> dataList)
        {
            string strSql = string.Format("select count(c.OrderTypeid) from OrderType c  " +
    "where c.OrderTypename='{0}'", strList["OrderType"]);
            int cont = Convert.ToInt32(OracleHelper.GetSingle(strSql));
            if (cont > 0)
            {
                result = true;
                return;
            }

            #region  生产订单类型
            ClientAPIEntity dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Name";
            dataEntity.ClientDataValue = strList["OrderType"];
            dataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Description";
            dataEntity.ClientDataValue = strList["OrderTypeDes"];
            dataList.Add(dataEntity);
            result = clientData.CreateModelByStandard("OrderTypeMaintDoc", "OrderTypeMaint", "new", dataList, ref resultInfo);
            #endregion
        }

        private static Dictionary<string, List<ClientAPIEntity>> FillAttributes(DataTable dtAttribute)
        {
            Dictionary<string, List<ClientAPIEntity>> m_ChildList = new Dictionary<string, List<ClientAPIEntity>>();
            for (int i = 0; i < dtAttribute.Rows.Count; i++)
            {
                List<ClientAPIEntity> m_Child = new List<ClientAPIEntity>();
                ClientAPIEntity entity = new ClientAPIEntity();

                entity.ClientDataTypeEnum = DataTypeEnum.DataField;
                entity.ClientDataName = "Name";
                entity.ClientDataValue = dtAttribute.Rows[i]["Name"].ToString();
                m_Child.Add(entity);

                entity = new ClientAPIEntity();
                entity.ClientDataTypeEnum = DataTypeEnum.DataField;
                entity.ClientDataName = "AttributeValue";
                entity.ClientDataValue = dtAttribute.Rows[i]["AttributeValue"].ToString();
                m_Child.Add(entity);

                entity = new ClientAPIEntity();
                entity.ClientDataTypeEnum = DataTypeEnum.DataField;
                entity.ClientDataName = "IsExpression";
                entity.ClientDataValue = "false";
                m_Child.Add(entity);

                entity = new ClientAPIEntity();
                entity.ClientDataTypeEnum = DataTypeEnum.DataField;
                entity.ClientDataName = "DataType";
                entity.ClientDataValue = "4";
                m_Child.Add(entity);

                m_ChildList.Add(i.ToString(), m_Child);
            }
            return m_ChildList;
        }

        public void GetContainerID(string strProductName, ref string strProductRev)
        {
            string strSql = string.Format("select pb.productname,p.productrevision from productbase pb " +
                "left join product p on p.productid=pb.revofrcdid where pb.productnam " +
                "where c.containername='{0}'", strProductName);
            DataSet myDS = OracleHelper.Query(strSql);
            strProductRev = myDS.Tables[0].Rows[0]["productrevision"].ToString().Trim();
        }

        public string GetContainerID(string strContainerName)//update:Wangjh 20171106 add:isOther
        {
            string strSql = string.Format("select c.containername,c.containerid  from container c where upper(c.containername)='{0}'", strContainerName.ToUpper());

            DataSet myDS = new DataSet();
            myDS = OracleHelper.Query(strSql);
            if (myDS.Tables[0].Rows.Count == 0)
            {
                myDS = OracleHelper.Query(strSql, true);
            }

            return myDS.Tables[0].Rows[0]["containerid"].ToString().Trim();
        }

        /// <summary>
        /// 根据分厂代码获取分厂名称
        /// </summary>
        /// <param name="factoryCode"></param>
        /// <returns></returns>
        public string GetFacorybyCode(string factoryCode)
        {
            string strSql = @"select f.factoryname,ua.attributevalue,ua.userattributename from factory f 
                                left join userattribute ua on ua.parentid =f.factoryid 
                                where ua.userattributename='分厂代码'";
            strSql += string.Format("and ua.attributevalue='{0}'", factoryCode);
            DataSet myDS = OracleHelper.Query(strSql.ToString());
            if (myDS == null)
            {
                return factoryCode;
            }
            if (myDS.Tables.Count == 0)
            {
                return factoryCode;
            }
            if (myDS.Tables[0].Rows.Count == 0)
            {
                return factoryCode;
            }

            string factoryname = myDS.Tables[0].Rows[0]["factoryname"].ToString();
            return factoryname;
        }

        public bool MfgOrderExist(string ordername, ref int attcount, Boolean isOther)
        {
            string strSql = string.Format("select c.mfgordername,c.mfgorderid from mfgorder c  " +
                "where c.mfgordername='{0}'", ordername);
            DataSet myDS = new DataSet();
            if (isOther == true)
            {
                myDS = OracleHelper.Query(strSql.ToString(), true);
            }
            else
            {
                myDS = OracleHelper.Query(strSql.ToString());
            }


            if (myDS == null)
            {
                return false;
            }
            if (myDS.Tables.Count == 0)
            {
                return false;
            }
            if (myDS.Tables[0].Rows.Count == 0)
            {
                return false;
            }
            strSql = string.Format("SELECT COUNT(C.USERATTRIBUTEID) FROM USERATTRIBUTE C " +
                "WHERE C.PARENTID = '{0}'", myDS.Tables[0].Rows[0]["mfgorderid"]);
            if (isOther == true)
            {
                attcount = Convert.ToInt32(OracleHelper.GetSingle(strSql.ToString(), true));
            }
            else
            {
                attcount = Convert.ToInt32(OracleHelper.GetSingle(strSql.ToString()));
            }


            return true;
        }

        public string SaveMaterial(Dictionary<string, string> strList, Boolean isOtherConn)//add:Wangjh 20170925 增加参数是否选择外部服务器地址
        {
            string strSql = string.Format("select c.containername,cl.containerlevelname from container c  " +
                "left join containerlevel cl on cl.containerlevelid=c.levelid  " +
                "where c.containername like '{0}%'", strList["containerName"].Trim());
            DataSet myDS;
            myDS = isOtherConn ? OracleHelper.Query(strSql.ToString(), true) : OracleHelper.Query(strSql.ToString());//add:Wangjh 20170925 增加判断是否选择查询外部服务器

            if (myDS == null)
            {
                return "批次不存在1";
            }
            if (myDS.Tables.Count == 0)
            {
                return "批次不存在2";
            }
            if (myDS.Tables[0].Rows.Count == 0)
            {
                return "批次不存在3";
            }
            string strCotnaienr = myDS.Tables[0].Rows[0]["containername"].ToString();
            string strCotnaienrLevel = myDS.Tables[0].Rows[0]["containerlevelname"].ToString();
            APICommon api = new APICommon();
            uMESProcessResult result = new uMESProcessResult();
            List<ContainerStartInfo> list = new List<ContainerStartInfo>();
            foreach (KeyValuePair<string, string> kvp in strList)
            {
                if (kvp.Key == "mfgordername")
                    continue;
                if (kvp.Key == "containerName")
                    continue;

                ContainerStartInfo conEntity = new ContainerStartInfo();
                conEntity.ContainerName = strCotnaienr;
                conEntity.Level = strCotnaienrLevel;
                conEntity.AttributeName = kvp.Key;
                conEntity.attributeValue = kvp.Value;
                LogHelp.WriteLog(kvp.Key + ":" + kvp.Value);
                list.Add(conEntity);
            }


            result = isOtherConn ? api.SetUserAttribute(list, true) : api.SetUserAttribute(list, false);//add:Wangjh 20170925 增加参数是否选择外部服务器地址


            LogHelp.WriteLog(String.Format("result:{0}", result));
            if (result.Result)
            {
                LogHelp.WriteLog(m_strSuccess);
                return m_strSuccess;
            }
            else
            {
                LogHelp.WriteLog(String.Format("result.Message:{0}", result.Message));
                return result.Message;
            }
        }

        /// <summary>
        /// 直接更新属性
        /// create:Wangjh 20171211
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        public string SaveMaterialNew(Dictionary<string, string> strList)
        {
            try
            {


                string strSql = string.Format("select cci.isinstore,cci.techniquedate,c.containername,cl.containerlevelname,c.containerID from container c  " +
                    "left join containerlevel cl on cl.containerlevelid=c.levelid  " +
                    " left join containercurrentinfo cci on cci.containerid=c.containerid " +
                    "where upper(c.containername) = '{0}'", strList["containerName"].Trim().ToUpper());
                DataSet myDS;
                myDS = OracleHelper.Query(strSql.ToString());

                if (myDS == null)
                {
                    return "批次不存在1";
                }
                if (myDS.Tables.Count == 0)
                {
                    return "批次不存在2";
                }
                if (myDS.Tables[0].Rows.Count == 0)
                {
                    return "批次不存在3";
                }
                if (myDS.Tables[0].Rows[0].IsNull("techniquedate"))
                {
                    return "批次未校对不接收！！！";
                }
                if (myDS.Tables[0].Rows[0]["isinstore"].ToString() == "1")
                {
                    return "批次已入库不接收！！！";
                }

                string strCotnaienr = myDS.Tables[0].Rows[0]["containername"].ToString();

                DataTable attributeDt = GetAttribute(strList["containerName"]);//查询批次所有属性
                DataTable containerDt = myDS.Tables[0].DefaultView.ToTable(true, "ContainerID", "containername");//筛选所有ContaineriID
                //update:Wangjh 20181115
                foreach (DataRow containerRow in containerDt.Rows)
                {
                    APICommon ap = new APICommon();
                    ContainerStartInfo con = new ContainerStartInfo();
                    List<ContainerStartInfo> m_DataList = new List<ContainerStartInfo>();
                    foreach (string key in strList.Keys)
                    {
                        if (key == "containerName")
                        {
                            continue;
                        }
                        DataRow[] drs = attributeDt.Select(string.Format("ContainerID='{0}' and userattributename='{1}'", containerRow["ContainerID"].ToString(), key));
                        if (drs.Length == 0)//批次中无此属性
                        {
                            //InsertAttributeInfo(containerRow["containerName"].ToString(), key, strList[key]);  
                            con = new ContainerStartInfo();
                            con.ContainerName = containerRow["containerName"].ToString();
                            con.Level = "Lot";
                            con.AttributeName = key;
                            con.attributeValue = strList[key];
                            m_DataList.Add(con);
                        }
                        else
                        {
                            UpdateAttributeInfo(strList[drs[0]["userattributename"].ToString()], drs[0]["userattributeid"].ToString());
                        }

                    }
                    if (m_DataList.Count > 0)
                        ap.SetUserAttribute(m_DataList, false);

                }
                //


            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return m_strSuccess;

        }
        /// <summary>
        /// 存放多个的熔炉号
        /// add:Wangjh 20180613
        /// </summary>
        /// <param name="strValues"></param>
        /// <param name="containerNames"></param>
        /// <returns></returns>
        public Boolean UpdateBatchcomments(string strValues, string containerName)
        {
            string strSql = string.Format(@"UPDATE container c SET c.batchcomments='{0}' WHERE upper(c.containername)='{1}'", strValues, containerName.ToUpper());
            int i = OracleHelper.ExecuteSql(strSql);
            if (i > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 获取批次属性
        /// create:Wangjh 20171211
        /// </summary>
        /// <param name="containerName"></param>
        /// <returns></returns>
        public DataTable GetAttribute(string containerName)
        {
            string strSql = @"select c.containername,c.containerID,ut.userattributename,ut.attributevalue,ut.userattributeid from userattribute ut
                                left join container c on c.containerid=ut.parentid
                                where c.status=1";
            strSql += string.Format(" and c.containername like '{0}%'", containerName);
            strSql += " group by c.containername,c.containerID,ut.userattributename,ut.attributevalue,ut.userattributeid";

            return OracleHelper.Query(strSql).Tables[0];
        }

        /// <summary>
        /// 插入属性
        /// create:Wangjh 20171211
        /// </summary>
        /// <param name="attributevalue"></param>
        /// <param name="containerID"></param>
        /// <param name="userattributeName"></param>
        /// <returns></returns>
        public string InsertAttributeInfo(string containerName, string attrName, string attrValue)
        {
            CamstarClientAPI clientData = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(), ConfigurationManager.AppSettings["CamstarPassword"].ToString());
            string strInfo = "";
            //clientData.ContainerAtterMaint(containerName,"Lot",p_dataEntityList ,ref strInfo );
            List<ClientAPIEntity> m_DataList = new List<ClientAPIEntity>();
            ClientAPIEntity DataEntity = new ClientAPIEntity();
            DataEntity.ClientDataTypeEnum = DataTypeEnum.ContainerField;
            DataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            DataEntity.ClientDataName = "Container";
            DataEntity.ClientDataValue = containerName;
            DataEntity.ClientOtherValue = "Lot";
            m_DataList.Add(DataEntity);
            //增加属性值
            Dictionary<String, List<ClientAPIEntity>> p_ChildEntity = new Dictionary<String, List<ClientAPIEntity>>();
            List<ClientAPIEntity> p_dataEntityList = new List<ClientAPIEntity>();
            DataEntity = new ClientAPIEntity();
            DataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            DataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            DataEntity.ClientDataName = "Name";
            DataEntity.ClientDataValue = attrName;
            p_dataEntityList.Add(DataEntity);

            DataEntity = new ClientAPIEntity();
            DataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            DataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            DataEntity.ClientDataName = "DataType";
            DataEntity.ClientDataValue = "4";
            p_dataEntityList.Add(DataEntity);

            DataEntity = new ClientAPIEntity();
            DataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            DataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            DataEntity.ClientDataName = "AttributeValue";
            DataEntity.ClientDataValue = attrValue;
            p_dataEntityList.Add(DataEntity);
            p_ChildEntity.Add("0", p_dataEntityList);
            //
            clientData.RunTxnServiceHasSubentity("ContainerAttrMaintDoc", "ContainerAttrMaint", m_DataList, "ServiceDetails", p_ChildEntity, ref strInfo);

            return strInfo;
        }

        /// <summary>
        /// 更新批次属性
        /// create:Wangjh 20171211
        /// </summary>
        /// <param name="attributevalue"></param>
        /// <param name="userattributeid"></param>
        /// <returns></returns>
        public Boolean UpdateAttributeInfo(string attributevalue, string userattributeid)
        {
            string updateSql = @" update userattribute ut set ut.attributevalue=:attributevalue where ut.userattributeid=:userattributeid";

            OracleParameter[] insertParam = new OracleParameter[2];
            insertParam[0] = new OracleParameter(":attributevalue", OracleType.VarChar);
            insertParam[0].Direction = ParameterDirection.Input;
            insertParam[0].Value = attributevalue;

            insertParam[1] = new OracleParameter(":userattributeid", OracleType.VarChar);
            insertParam[1].Direction = ParameterDirection.Input;
            insertParam[1].Value = userattributeid;

            int i = OracleHelper.ExecuteSql(updateSql, insertParam);
            if (i > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 更新派工准备记录状态
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        public string SaveDispatchingRecordStatus(Dictionary<string, string> strList)
        {

            string strSQL = "update WRITETOERPRECORD t set t.recordstatus=:status where t.recordid in (:recordid) and t.recordtype=:type";
            OracleParameter[] insertParam = new OracleParameter[3];

            insertParam[0] = new OracleParameter(":status", OracleType.VarChar, 255);
            insertParam[0].Value = strList["Status"];

            insertParam[1] = new OracleParameter(":recordid", OracleType.VarChar, 255);
            insertParam[1].Value = strList["ArrangementsID"].ToLower().Replace("'", null);

            insertParam[2] = new OracleParameter(":type", OracleType.VarChar, 255);
            insertParam[2].Value = strList["Type"];

            int i = OracleHelper.ExecuteSql(strSQL, insertParam);
            if (i > 0)
                return "更新记录条数:" + i;
            else
                return "没有可更新记录";

        }

        public DataTable GetProductByMfgorder(string mfgorderName)
        {

            string strSql = @"
                            SELECT pb2.productname FROM mfgorder m
                            LEFT JOIN productbase pb ON pb.productbaseid=m.productbaseid
                            LEFT JOIN product p ON p.productid=NVL(pb.revofrcdid,m.productid)
                            LEFT JOIN productbase pb2 ON pb2.productbaseid=p.productbaseid
                            ";

            strSql += string.Format("WHERE m.mfgordername='{0}'", mfgorderName);
            return OracleHelper.Query(strSql).Tables[0];
        }

        public string InsertCollectERPMaterial(Dictionary<string, string> para)
        {
            string strSql = @"INSERT INTO CollectERPMaterial
                            (COLLECTERPMATERIALID, CREATEDATE, ISAUTOPLAN, ISNONCONFORMING，MFGORDERNAME,ORIGINALPRODUCTNAME,
                            PRODUCTBATCHNO,PRODUCTNAME,QTY,UOM,iserp,SOURCEQTY) 
                            VALUES (:COLLECTERPMATERIALID, sysdate, :ISAUTOPLAN, :ISNONCONFORMING, :MFGORDERNAME,:ORIGINALPRODUCTNAME
                            ,:PRODUCTBATCHNO,:PRODUCTNAME,:QTY,:UOM,1,:QTY)";
            OracleParameter[] insertParam = new OracleParameter[9];

            insertParam[0] = new OracleParameter();
            insertParam[0].ParameterName = ":COLLECTERPMATERIALID";
            insertParam[0].OracleType = OracleType.VarChar;
            insertParam[0].Direction = ParameterDirection.Input;
            insertParam[0].Value = Guid.NewGuid().ToString();

            insertParam[1] = new OracleParameter();
            insertParam[1].ParameterName = ":ISAUTOPLAN";
            insertParam[1].OracleType = OracleType.VarChar;
            insertParam[1].Direction = ParameterDirection.Input;
            insertParam[1].Value = para["ISAUTOPLAN"];

            insertParam[2] = new OracleParameter();
            insertParam[2].ParameterName = ":ISNONCONFORMING";
            insertParam[2].OracleType = OracleType.VarChar;
            insertParam[2].Direction = ParameterDirection.Input;
            insertParam[2].Value = para["ISNONCONFORMING"];

            insertParam[3] = new OracleParameter();
            insertParam[3].ParameterName = ":MFGORDERNAME";
            insertParam[3].OracleType = OracleType.VarChar;
            insertParam[3].Direction = ParameterDirection.Input;
            insertParam[3].Value = para["MFGORDERNAME"];

            insertParam[4] = new OracleParameter();
            insertParam[4].ParameterName = ":ORIGINALPRODUCTNAME";
            insertParam[4].OracleType = OracleType.VarChar;
            insertParam[4].Direction = ParameterDirection.Input;
            insertParam[4].Value = para["ORIGINALPRODUCTNAME"];

            insertParam[5] = new OracleParameter();
            insertParam[5].ParameterName = ":PRODUCTBATCHNO";
            insertParam[5].OracleType = OracleType.VarChar;
            insertParam[5].Direction = ParameterDirection.Input;
            insertParam[5].Value = para["PRODUCTBATCHNO"];

            insertParam[6] = new OracleParameter();
            insertParam[6].ParameterName = ":PRODUCTNAME";
            insertParam[6].OracleType = OracleType.VarChar;
            insertParam[6].Direction = ParameterDirection.Input;
            insertParam[6].Value = para["PRODUCTNAME"];

            insertParam[7] = new OracleParameter();
            insertParam[7].ParameterName = ":QTY";
            insertParam[7].OracleType = OracleType.Number;
            insertParam[7].Direction = ParameterDirection.Input;
            insertParam[7].Value = para["QTY"];

            insertParam[8] = new OracleParameter();
            insertParam[8].ParameterName = ":UOM";
            insertParam[8].OracleType = OracleType.VarChar;
            insertParam[8].Direction = ParameterDirection.Input;
            insertParam[8].Value = para["UOM"];

            if (para.ContainsKey("IsOtherConn"))
            {
                int i = OracleHelper.ExecuteSql(strSql, true, insertParam);
                if (i > 0)
                    return "";
                else
                    return "数据创建失败";

            }
            else
            {
                int i = OracleHelper.ExecuteSql(strSql, insertParam);
                if (i > 0)
                    return "";
                else
                    return "数据创建失败";
            }

        }

        //add by yuxj 20170613
        public string UpdateUnqualifiedData(Dictionary<string, string> para)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("UPDATE ContainerNonconformingInfo SET ");
            if (para.ContainsKey("QMNUM"))
            {
                sb.AppendFormat("QMNUM = nvl('" + para["QMNUM"] + "',null), ");
            }

            if (para.ContainsKey("ZBHGDH"))
            {
                sb.AppendFormat("ZBHGDH = nvl('" + para["ZBHGDH"] + "',null), ");
            }

            if (para.ContainsKey("ZSLJL"))
            {
                sb.AppendFormat("ZSLJL = nvl('" + para["ZSLJL"] + "',null), ");
            }

            if (para.ContainsKey("ZBZ2"))
            {
                sb.AppendFormat("ZBZ2 = nvl('" + para["ZBZ2"] + "',null), ");
            }

            if (para.ContainsKey("ZYWLPC2"))
            {
                sb.AppendFormat("ZYWLPC2 = nvl('" + para["ZYWLPC2"] + "',null), ");
            }

            if (para.ContainsKey("ZJYBH"))
            {
                sb.AppendFormat("ZJYBH = nvl('" + para["ZJYBH"] + "',null), ");
            }

            if (para.ContainsKey("ZSFGL"))
            {
                sb.AppendFormat("ZSFGL = nvl('" + para["ZSFGL"] + "',null) ");
            }

            sb.AppendFormat(" WHERE containernonconforminginfoid='" + para["RECORDID"] + "' ");


            //update:Wangjh 20170925 注释
            //if (para.ContainsKey("MATNR"))
            //{
            //    if (para["MATNR"] != string.Empty)
            //    {
            //        sb.AppendFormat("and MATNR = '" + para["MATNR"] + "' ");
            //    }
            //    else
            //        sb.AppendLine("and MATNR is null ");
            //}

            //if (para.ContainsKey("FERTAUFNR"))
            //{
            //    if (para["FERTAUFNR"] != string.Empty)
            //    {
            //        sb.AppendFormat("and FERTAUFNR = '" + para["FERTAUFNR"] + "' ");
            //    }
            //    else
            //        sb.AppendLine("and FERTAUFNR is null ");
            //}

            //if (para.ContainsKey("ZMESGX"))
            //{
            //    if (para["ZMESGX"] != string.Empty)
            //    {
            //        sb.AppendFormat("and ZMESGX = '" + para["ZMESGX"] + "' ");
            //    }
            //    else
            //        sb.AppendLine("and ZMESGX is null ");
            //}

            //if (para.ContainsKey("UVORN"))
            //{
            //    if (para["UVORN"] != string.Empty)
            //    {
            //        sb.AppendFormat("and UVORN = '" + para["UVORN"] + "' ");
            //    }
            //    else
            //        sb.AppendLine("and UVORN is null ");
            //}

            // if (para.ContainsKey("ZLPH2"))
            //{
            //    if (para["ZLPH2"] != string.Empty)
            //    {
            //        sb.AppendFormat("and ZLPH2 = '" + para["ZLPH2"] + "' ");
            //    }
            //    else
            //        sb.AppendLine("and ZLPH2 is null ");
            //}

            // if (para.ContainsKey("ZPCH2"))
            //{
            //    if (para["ZPCH2"] != string.Empty)
            //    {
            //        sb.AppendFormat("and ZPCH2 = '" + para["ZPCH2"] + "' ");
            //    }
            //    else
            //        sb.AppendLine("and ZPCH2 is null ");
            //}

            // if (para.ContainsKey("ZGD2"))
            //{
            //    if (para["ZGD2"] != string.Empty)
            //    {
            //        sb.AppendFormat("and ZGD2 = '" + para["ZGD2"] + "' ");
            //    }
            //    else
            //        sb.AppendLine("and ZGD2 is null ");
            //}

            if (para.ContainsKey("IsOtherConn"))
            {
                int i = OracleHelper.ExecuteSql(sb.ToString(), true);
                if (i > 0)
                    return "";
                else
                    return "数据创建失败";
            }
            else
            {
                int i = OracleHelper.ExecuteSql(sb.ToString());
                if (i > 0)
                    return "";
                else
                    return "数据创建失败";
            }
        }

        //如下方法在number字段报错时难以调试，故注释掉换另一写法,yuxj 20170613
        /*
        public string UpdateUnqualifiedDataOld(Dictionary<string, string> para)
        {
            string strSql = "UPDATE ContainerNonconformingInfo SET QMNUM = :QMNUM,ZBHGDH = :ZBHGDH,ZSLJL = :ZSLJL,ZBZ2 = :ZBZ2," +
                            "ZYWLPC2 = :ZYWLPC2,ZJYBH = :ZJYBH,ZSFGL = :ZSFGL" +
                            " WHERE MATNR = :MATNR and  FERTAUFNR = :FERTAUFNR and ZMESGX = :ZMESGX and UVORN = :UVORN and ZLPH2 = :ZLPH2 " +
                            " and  ZPCH2 = :ZPCH2 and ZGD2 = :ZGD2";
            OracleParameter[] insertParam = new OracleParameter[14];

            insertParam[0] = new OracleParameter();
            insertParam[0].ParameterName = ":QMNUM";
            insertParam[0].OracleType = OracleType.VarChar;
            insertParam[0].Direction = ParameterDirection.Input;
            insertParam[0].Value = para["QMNUM"];

            insertParam[1] = new OracleParameter();
            insertParam[1].ParameterName = ":ZBHGDH";
            insertParam[1].OracleType = OracleType.VarChar;
            insertParam[1].Direction = ParameterDirection.Input;
            insertParam[1].Value = para["ZBHGDH"];

            insertParam[2] = new OracleParameter();
            insertParam[2].ParameterName = ":ZSLJL";
            insertParam[2].OracleType = OracleType.VarChar;
            insertParam[2].Direction = ParameterDirection.Input;
            insertParam[2].Value = para["ZSLJL"];

            insertParam[3] = new OracleParameter();
            insertParam[3].ParameterName = ":ZBZ2";
            insertParam[3].OracleType = OracleType.VarChar;
            insertParam[3].Direction = ParameterDirection.Input;
            insertParam[3].Value = para["ZBZ2"];

            insertParam[4] = new OracleParameter();
            insertParam[4].ParameterName = ":ZYWLPC2";
            insertParam[4].OracleType = OracleType.VarChar;
            insertParam[4].Direction = ParameterDirection.Input;
            insertParam[4].Value = para["ZYWLPC2"];

            insertParam[5] = new OracleParameter();
            insertParam[5].ParameterName = ":ZJYBH";
            insertParam[5].OracleType = OracleType.VarChar;
            insertParam[5].Direction = ParameterDirection.Input;
            insertParam[5].Value = para["ZJYBH"];

            insertParam[6] = new OracleParameter();
            insertParam[6].ParameterName = ":ZSFGL";
            insertParam[6].OracleType = OracleType.VarChar;
            insertParam[6].Direction = ParameterDirection.Input;
            insertParam[6].Value = para["ZSFGL"];

            insertParam[7] = new OracleParameter();
            insertParam[7].ParameterName = ":MATNR";
            insertParam[7].OracleType = OracleType.Number;
            insertParam[7].Direction = ParameterDirection.Input;
            insertParam[7].Value = para["MATNR"];

            insertParam[8] = new OracleParameter();
            insertParam[8].ParameterName = ":FERTAUFNR ";
            insertParam[8].OracleType = OracleType.VarChar;
            insertParam[8].Direction = ParameterDirection.Input;
            insertParam[8].Value = para["FERTAUFNR"];

            insertParam[9] = new OracleParameter();
            insertParam[9].ParameterName = ":ZMESGX";
            insertParam[9].OracleType = OracleType.VarChar;
            insertParam[9].Direction = ParameterDirection.Input;
            insertParam[9].Value = para["ZMESGX"];

            insertParam[10] = new OracleParameter();
            insertParam[10].ParameterName = ":UVORN";
            insertParam[10].OracleType = OracleType.VarChar;
            insertParam[10].Direction = ParameterDirection.Input;
            insertParam[10].Value = para["UVORN"];

            insertParam[11] = new OracleParameter();
            insertParam[11].ParameterName = ":ZLPH2";
            insertParam[11].OracleType = OracleType.VarChar;
            insertParam[11].Direction = ParameterDirection.Input;
            insertParam[11].Value = para["ZLPH2"];

            insertParam[12] = new OracleParameter();
            insertParam[12].ParameterName = ":ZPCH2";
            insertParam[12].OracleType = OracleType.VarChar;
            insertParam[12].Direction = ParameterDirection.Input;
            insertParam[12].Value = para["ZPCH2"];

            insertParam[13] = new OracleParameter();
            insertParam[13].ParameterName = ":ZGD2";
            insertParam[13].OracleType = OracleType.VarChar;
            insertParam[13].Direction = ParameterDirection.Input;
            insertParam[13].Value = para["ZGD2"];

            int i = OracleHelper.ExecuteSql(strSql, insertParam);
            if (i > 0)
                return "";
            else
                return "数据创建失败";
        }
        */
        #region 保存资源
        public string SaveResource(Dictionary<string, string> strList, Boolean isOtherConn)
        {
            CamstarClientAPI clientData;
            if (isOtherConn)
            {
                string[] tempStr = GetJXCamstarConn().Split('$');
                clientData = new CamstarClientAPI(tempStr[1].ToString(), tempStr[2].ToString(),
                 tempStr[0].ToString().Split(':').First(), tempStr[0].ToString().Split(':').Last());
            }
            else
            {
                clientData = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(), ConfigurationManager.AppSettings["CamstarPassword"].ToString());
            }
            string resultInfo = string.Empty;
            bool result = false;
            List<ClientAPIEntity> dataList = new List<ClientAPIEntity>();
            ClientAPIEntity dataEntity;
            string strSql = string.Format("select resourcefamilyname from resourcefamily  " +
                "where resourcefamilyname='{0}'", strList["ResourceFamily"]);
            DataSet myDS;
            myDS = isOtherConn ? OracleHelper.Query(strSql.ToString(), true) : OracleHelper.Query(strSql.ToString());//update:Wangjh 20170925
            if (myDS == null || myDS.Tables.Count == 0 || myDS.Tables[0].Rows.Count == 0)
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "Name";
                dataEntity.ClientDataValue = strList["ResourceFamily"];
                dataList.Add(dataEntity);
                result = clientData.CreateModelByStandard("ResourceFamilyMaintDoc", "ResourceFamilyMaint", "new",
                                                          dataList, ref resultInfo);
            }

            dataList.Clear();
            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Name";
            dataEntity.ClientDataValue = strList["Name"];
            dataList.Add(dataEntity);
            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntity.ClientDataName = "Description";
            dataEntity.ClientDataValue = strList["Description"];
            dataList.Add(dataEntity);

            //yuxj20221101 增加WorkCenterCode
            if (strList.ContainsKey("Notes"))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "Notes";
                dataEntity.ClientDataValue = strList["Notes"];
                dataList.Add(dataEntity);
            }

            if (strList.ContainsKey("WorkCenterCode"))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "WorkCenterCode";
                dataEntity.ClientDataValue = strList["WorkCenterCode"];
                dataList.Add(dataEntity);
            }

            if (strList.ContainsKey("ERPStatus"))
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientDataName = "ERPStatus";
                dataEntity.ClientDataValue = strList["ERPStatus"];
                dataList.Add(dataEntity);
            }

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientDataName = "ResourceFamily";
            dataEntity.ClientDataValue = strList["ResourceFamily"];
            dataList.Add(dataEntity);
            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataEntity.ClientDataName = "Factory";
            dataEntity.ClientDataValue = strList["Factory"];
            dataList.Add(dataEntity);

            strSql = "select t.resourceename from resourcedef t  where t.resourcename='" + strList["Name"] + "'";

            DataSet tmpSet;
            tmpSet = isOtherConn ? OracleHelper.Query(strSql, true) : OracleHelper.Query(strSql);//update:Wangjh 20170925
            if (tmpSet.Tables[0].Rows.Count == 0)
            {

                result = clientData.CreateModelByStandard("ResourceMaintDoc", "ResourceMaint", "new",
                                                           dataList, ref resultInfo);
            }
            else
            {
                result = clientData.UpdateModelByStandard("ResourceMaintDoc", "ResourceMaint", strList["Name"], "", dataList, ref resultInfo);
            }

            if (result)
            {
                return "";
            }
            else
            {
                return resultInfo;
            }
        }
        #endregion

        /// <summary>
        /// 根据父卡查询子卡
        /// create:Wangjh 20171129
        /// </summary>
        /// <param name="containerName"></param>
        /// <returns></returns>
        public DataTable QueryChildContainer(string containerName)
        {
            string strSql = @"
                            select c2.containername,c2.containerid from container c
                            left join container c2 on c2.parentcontainerid=c.containerid
                            where  c2.parentcontainerid is not null and c.parentcontainerid is null and c2.status=1
                            ";
            strSql += string.Format(" and c.containername='{0}' ", containerName);
            strSql += " order by c2.containername asc";
            return OracleHelper.Query(strSql).Tables[0];

        }

        public string SaveChildContainerMaterial(Dictionary<string, string> strList)
        {
            string updateSql = @"update container c set c.batchcomments=:batchcomments  where upper(c.containername)=:containername";
            OracleParameter[] updateParam = new OracleParameter[2];

            updateParam[0] = new OracleParameter();
            updateParam[0].ParameterName = ":batchcomments";
            updateParam[0].OracleType = OracleType.VarChar;
            updateParam[0].Direction = ParameterDirection.Input;
            updateParam[0].Value = strList["熔炉号母"] + " 实发数：" + strList["实发数/顺序号"];

            updateParam[1] = new OracleParameter();
            updateParam[1].ParameterName = ":containername";
            updateParam[1].OracleType = OracleType.VarChar;
            updateParam[1].Direction = ParameterDirection.Input;
            updateParam[1].Value = strList["containerName"];

            int i = OracleHelper.ExecuteSql(updateSql, false, updateParam);
            if (i > 0)
                return "成功";
            else
                return "失败";
        }

        /// <summary>
        /// 根据物料编码获取产品名称 
        /// add:Wangjh 20211013
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public DataTable GetProductNameByMaterialCode(string code)
        {
            string strSql = @" select pb.productname,p.productrevision,pt.producttypename,p.description from product p
left join productbase pb on pb.productbaseid=p.productbaseid 
left join producttype pt on pt.producttypeid=p.producttypeid
where p.materialcode='" + code + "' and p.productid=pb.revofrcdid and p.materialcode!=pb.productname AND pt.producttypename!='子工艺虚拟件'";
            return OracleHelper.Query(strSql).Tables[0];
        }

        public string CreateXML(string strmessage, bool isSuccess)
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode sysNode = doc.CreateElement("SysName");
            sysNode.InnerText = "APP_MES";
            XmlNode resultNode = doc.CreateElement("isSuccess");
            resultNode.InnerText = isSuccess.ToString().ToLower();
            XmlNode msgNode = doc.CreateElement("message");
            msgNode.InnerText = strmessage;
            headerNode.AppendChild(sysNode);
            headerNode.AppendChild(resultNode);
            headerNode.AppendChild(msgNode);
            ReqNode.AppendChild(headerNode);
            XmlNode documentNode = doc.CreateElement("document");
            documentNode.AppendChild(doc.CreateCDataSection(""));
            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }

        /// <summary>
        /// 组别件订单,继承源件号的子件号信息 add:Wangjh 20200326
        /// </summary>
        /// <param name="pdmProductName">原件号</param>
        /// <param name="productName">组别件号</param>
        /// <param name="revision">组别件版本</param>
        public void ineritSubProductInfo(string pdmProductName, string productName, string revision)
        {

            string strSql = @"SELECT pb2.productname,pp.* FROM productsubproduct pp
LEFT JOIN productbase pb ON pb.revofrcdid=pp.productid
LEFT JOIN product p ON p.productid=pp.subproductid
LEFT JOIN productbase pb2 ON pb2.productbaseid=p.productbaseid
WHERE pb.productname='" + pdmProductName + "'";

            DataTable dt = OracleHelper.Query(strSql).Tables[0];

            if (dt.Rows.Count == 0)
                return;

            string productSql = @" 
SELECT p.productid,p.workflowid FROM product p 

LEFT JOIN productbase pb ON pb.productbaseid=p.productbaseid

WHERE pb.productname='{0}' AND p.productrevision='{1}'";

            DataTable dt2 = OracleHelper.Query(string.Format(productSql, productName, revision)).Tables[0];

            if (dt2.Rows.Count == 0)
                return;
            string productid = dt2.Rows[0]["productid"].ToString();

            strSql = "select * from productsubproduct pp where pp.productid='" + productid + "'";

            string inserSql = "INSERT INTO productsubproduct pp (pp.productid,pp.subproductid) VALUES('{0}','{1}')";

            foreach (DataRow dr in dt.Rows)
            {
                string newSubProductName = dr["productname"].ToString().Replace(pdmProductName, productName);//组别件的子件号
                string newSubProductID = "";

                Dictionary<string, string> strList = new Dictionary<string, string>();
                strList["Revision"] = revision;

                DataTable productDt = GetProductByNameAndRev(newSubProductName, revision);

                string strMsg = "";

                if (productDt.Rows.Count > 0)//已存在组别件子件号信息
                {
                    strList["ProductID"] = productDt.Rows[0]["ProductID"].ToString();
                    strList["productName"] = productDt.Rows[0]["productName"].ToString();
                    strList["ProductType"] = productDt.Rows[0]["producttypename"].ToString();
                    DataTable OrgSubProductDt = GetProductByNameAndRev(dr["productname"].ToString(), strList["Revision"]);//原来子件号信息
                    //更新组别件子件号的信息
                    UpdateProductByProduct(strList, OrgSubProductDt, ref strMsg);

                }
                else
                {
                    strList["PdmProductName"] = dr["productname"].ToString();
                    strList["productName"] = newSubProductName;
                    strList["ProductType"] = "子工艺虚拟件";
                    //创建组别件子件号
                    CopyProduct(strList, ref strMsg);

                }

                DataTable newSubProductDt = OracleHelper.Query(string.Format(productSql, newSubProductName, revision)).Tables[0];

                if (newSubProductDt.Rows.Count == 0)
                    continue;

                newSubProductID = newSubProductDt.Rows[0]["ProductID"].ToString();

                //更新productworkflowmapping

                string pwSql = "SELECT * FROM  productworkflowmapping pw WHERE pw.productid='{0}' AND pw.workflowid='{1}'";

                if (OracleHelper.Query(string.Format(pwSql, newSubProductID, newSubProductDt.Rows[0]["workflowid"].ToString())).Tables[0].Rows.Count == 0)
                {
                    pwSql = "INSERT INTO productworkflowmapping pw (pw.productid,pw.workflowid) VALUES('{0}','{1}')";

                    OracleHelper.ExecuteSql(string.Format(pwSql, newSubProductID, newSubProductDt.Rows[0]["workflowid"].ToString()));
                }
                //

                if (newSubProductID == "")
                    continue;

                if (OracleHelper.Query(strSql + " and pp.subproductid='" + newSubProductID + "'").Tables[0].Rows.Count > 0)
                    continue;
                OracleHelper.ExecuteSql(string.Format(inserSql, productid, newSubProductID));

            }

        }

        /// <summary>
        /// erp和tc系统productname不一致情况处理
        /// add:Wangjh 20222/1/6
        /// </summary>
        public void erpAndTcProductNameHandle(ref string productName)
        {
            string strSql = string.Format("SELECT pb.productname FROM productbase pb WHERE upper(pb.productname)='{0}' ", productName);
            var temp = OracleHelper.GetSingle(strSql);

            if (temp != null)
            {
                productName = temp.ToString();
            }

        }

        /// <summary>
        /// 发料接口，批次第一个序自动报工
        /// add:Wangjh 20220221
        /// </summary>
        /// <param name="containerName"></param>
        public string ContainerFisrtAutoCheck(Dictionary<string, string> para)
        {
            if (string.IsNullOrWhiteSpace(para["XLR"]))
            {
                return "";
            }
            string strSql = "select 1 from container c where upper(c.containername) = '{0}'";

            if (OracleHelper.GetSingle(string.Format(strSql, para["containerName"].ToString().ToUpper())) == null)
            {
                return "下料报工检查---批次不存在";
            }

            strSql = @"SELECT c.containerid,w.workflowid,ws.workflowstepid,c.qty FROM containercurrentinfo c 
LEFT JOIN container oc ON oc.containerid=c.containerid
LEFT JOIN workflow w ON w.workflowid=DECODE(c.isinstore,-1, oc.mfgworkflowid,c.workflowid)
LEFT JOIN workflowstep ws ON ws.workflowid=w.workflowid AND ws.sequence=1
LEFT JOIN containercheckinfo cci ON cci.containerid=c.containerid AND cci.workflowstepid=ws.workflowstepid AND cci.isuse=0
WHERE upper(c.containername)='{0}' AND nvl(cci.containercheckinfoid,'0')='0'";
            DataTable baseDt = OracleHelper.Query(string.Format(strSql, para["containerName"].ToString().ToUpper())).Tables[0];

            if (baseDt.Rows.Count == 0)
                return "下料报工已存在";
            //人员验证
            string reportEmpID, checkEmpID = "";
            var temp = OracleHelper.GetSingle(string.Format("select employeeid from employee where employeename='{0}'", para["XLR"]));
            if (temp == null)
            {
                LogHelp.WriteLog("下料人：" + para["XLR"] + "未找到");
                return "下料人：" + para["XLR"] + "未找到";
            }
            else
            {
                reportEmpID = temp.ToString();
            }
            temp = OracleHelper.GetSingle(string.Format("select employeeid from employee where employeename='{0}'", para["XLJY"]));
            if (temp == null)
            {
                LogHelp.WriteLog("下料检验人：" + para["XLJY"] + "未找到");
                return "下料检验人：" + para["XLJY"] + "未找到";
            }
            else
            {
                checkEmpID = temp.ToString();
            }
            //各个数量
            int reportQty, passQty, lossQty = 0, defectqty = 0, reworkqty = 0;
            if (!int.TryParse(para["XLJS"], out reportQty))
            {
                LogHelp.WriteLog("下料数量：XLJS格式错误");
                return "下料数量：XLJS格式错误";
            }
            if (!int.TryParse(para["HGSL"], out passQty))
            {
                LogHelp.WriteLog("合格数量：HGSL格式错误");
                return "合格数量：HGSL格式错误";
            }
            if (!string.IsNullOrWhiteSpace(para["BFSL"]) && !int.TryParse(para["BFSL"], out lossQty))
            {
                LogHelp.WriteLog("报废数量：BFSL格式错误");
                return "报废数量：BFSL格式错误";
            }
            if (!string.IsNullOrWhiteSpace(para["CCSL"]) && !int.TryParse(para["CCSL"], out defectqty))
            {
                LogHelp.WriteLog("超差数量：CCSL格式错误");
                return "超差数量：CCSL格式错误";
            }
            if (!string.IsNullOrWhiteSpace(para["FXSL"]) && !int.TryParse(para["FXSL"], out reworkqty))
            {
                LogHelp.WriteLog("返修数量：FXSL格式错误");
                return "返修数量：FXSL格式错误";
            }
            if (lossQty >= int.Parse(baseDt.Rows[0]["qty"].ToString()))
            {
                LogHelp.WriteLog("报废数量不能大于在制数");
                return "报废数量不能大于在制数";
            }

            var sqls = new ArrayList();
            //报工
            string reportId = Guid.NewGuid().ToString();
            strSql = @"INSERT INTO containerstepworkreport csw (csw.containerstepworkreportid,csw.containerid,csw.workflowstepid,csw.isuse,csw.checktype,csw.workerid,
csw.qty,csw.selfcheckqualifiedqty,csw.selfcheckoutoftoleranceqty,csw.selfchecklossqty,csw.createdate,csw.lossqty) VALUES('{0}','{1}','{2}',0,25,'{3}','{4}','{5}','{6}','{7}',to_date('{8}','yyyy-mm-dd hh24:mi:ss'),'{9}')";
            strSql = string.Format(strSql, reportId, baseDt.Rows[0]["containerid"].ToString(), baseDt.Rows[0]["workflowstepid"].ToString(), reportEmpID, reportQty, passQty, defectqty, lossQty, para["XLSJ"], lossQty);
            sqls.Add(strSql);

            var childDt = OracleHelper.Query("select containerid from container where status!=0 and parentcontainerid='" + baseDt.Rows[0]["containerid"].ToString() + "' order by containerid desc").Tables[0];
            foreach (DataRow childRow in childDt.Rows)
            {
                strSql = @"INSERT INTO containerstepworkreportchild cswd (cswd.childcontainerid,cswd.containerstepworkreportid) VALUES ('{0}','{1}')";
                sqls.Add(string.Format(strSql, childRow["containerid"].ToString(), reportId));
            }
            //检验
            string checkID = Guid.NewGuid().ToString();
            strSql = @"INSERT INTO containercheckinfo cci (cci.containercheckinfoid,cci.containerstepworkreportid,cci.containerid,cci.workflowstepid,cci.checkerid,cci.checkqty,cci.acceptanceqty,cci.acceptanceqty2,cci.defectqty
,cci.reworkqty,cci.lossqty,cci.checktypenote,cci.createdate,cci.isuse) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',1,to_date('{11}','yyyy-mm-dd hh24:mi:ss'),0)";
            strSql = string.Format(strSql, checkID, reportId, baseDt.Rows[0]["containerid"].ToString(), baseDt.Rows[0]["workflowstepid"].ToString(), checkEmpID, reportQty, passQty + reworkqty + defectqty, passQty, defectqty, reworkqty, lossQty, para["JYSJ"]);
            sqls.Add(strSql);
            //数量报废,发料接口报废
            if (lossQty > 0)
            {
                strSql = @"INSERT INTO CheckQtyChangeRecord(Checkqtychangerecordid,Containercheckinfoid,Containerid,Changeqtytype,Isuse,Qty,Reasonid,Scrapsourcetype,Containerstepworkreportid,Createdate,
Employeeid,Workflowstepid)VALUES('{0}','{1}','{2}',2,0,'{3}',(SELECT lossreasonid FROM lossreason WHERE lossreasonname='发料接口报废') ,1,'{4}',Sysdate,'{5}','{6}')";
                int childNum = childDt.Rows.Count - 1;//最大序号
                if (childDt.Rows.Count > 0)
                {
                    for (int i = 0; i < lossQty; i++)
                    {
                        sqls.Add(string.Format(strSql, Guid.NewGuid().ToString(), checkID, childDt.Rows[childNum - i]["containerid"].ToString(),
                            -1, reportId, checkEmpID, baseDt.Rows[0]["workflowstepid"].ToString()));
                        //子序号批次关闭
                        sqls.Add("update  container set status=2 where containerid='" + childDt.Rows[childNum - i]["containerid"].ToString() + "'");
                    }
                }
                else
                {
                    sqls.Add(string.Format(strSql, Guid.NewGuid().ToString(), checkID, baseDt.Rows[0]["containerid"].ToString(),
                           0 - lossQty, reportId, checkEmpID, baseDt.Rows[0]["workflowstepid"].ToString()));
                }
            }
            strSql = string.Format("UPDATE container c SET c.qty = c.qty +({0}) WHERE c.containerid = '{1}'", 0 - lossQty, baseDt.Rows[0]["containerid"].ToString());
            sqls.Add(strSql);

            strSql = string.Format("UPDATE containercurrentinfo c SET c.qty = c.qty +({0}) WHERE c.containerid = '{1}'", 0 - lossQty, baseDt.Rows[0]["containerid"].ToString());
            sqls.Add(strSql);
            //备注信息
            strSql = "insert into containerstepattribute (CONTAINERID,WORKFLOWSTEPID,NOTES,CREATEEMPLOYEEID,CREATEDATE) values ('{0}','{1}','{2}','{3}',sysdate)";
            sqls.Add(string.Format(strSql, baseDt.Rows[0]["containerid"].ToString(), baseDt.Rows[0]["workflowstepid"].ToString(), para["BZ"], checkEmpID));
            OracleHelper.ExecuteSqlTran(sqls);

            return " 下料报工成功";

        }
        /// <summary>
        /// 更新工装工具批次上的订单id
        /// </summary>
        /// <param name="mfgorderName"></param>
        /// <param name="productname"></param>
        public void UpdateContainerMfgorder(string mfgorderName, string productname, string orderType)
        {
            string strSql = "SELECT mfgorderid FROM mfgorder m WHERE m.mfgordername='" + mfgorderName + "'";

            var mfgorderId = OracleHelper.GetSingle(strSql);
            if (mfgorderId == null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(mfgorderId.ToString()))
            {
                return;
            }

            if (OracleHelper.Query("select 1 from containercurrentinfo where mfgordername='" + mfgorderName + "'").Tables[0].Rows.Count > 0)
            {
                return;
            }
            if (OracleHelper.Query("select 1 from containercurrentinfo where productname='" + productname + "'").Tables[0].Rows.Count != 1)
            {
                return;
            }

            strSql = @"
BEGIN
UPDATE container c SET c.mfgorderid='{0}' WHERE c.containerid IN
(
SELECT cci.containerid FROM containercurrentinfo cci WHERE cci.productname='{1}' and cci.mfgorderid is null
);
UPDATE containercurrentinfo c SET c.mfgorderid='{0}',c.mfgordername='{2}',c.mfgordertype='{3}' WHERE c.productname='{1}' and c.mfgorderid is null;
END;";
            OracleHelper.ExecuteSql(string.Format(strSql, mfgorderId, productname, mfgorderName, orderType));

        }
        /// <summary>
        ///发料接口,释放平行作业暂停的批次
        /// add:Wangjh 2022/7/13
        /// </summary>
        /// <param name="containerName"></param>
        /// <param name="qcjy"></param>
        public void ReleaseContainerByPXZY(string containerName)
        {
            string strSql = @"SELECT cci.containerid,cci.containername,cci.productid,cci.productname,cci.qty,ot.opertype,ot.operreason FROM opercontainerrecord ot 
LEFT JOIN containercurrentinfo cci ON cci.containerid=ot.containerid
WHERE cci.ishold=1 AND ot.containername='{0}' 
ORDER BY ot.createdate DESC";
            DataTable dt = OracleHelper.Query(string.Format(strSql, containerName)).Tables[0];
            if (dt.Rows.Count == 0)
            {
                return;
            }
            if (dt.Rows[0]["opertype"].ToString() == "2" && dt.Rows[0]["operreason"].ToString() == "平行作业工序暂停")
            {
                strSql = @"BEGIN
UPDATE containercurrentinfo cci SET cci.ishold=0 WHERE cci.containerid='{0}';
INSERT INTO opercontainerrecord ot (ot.containerid,ot.containername,ot.operreason,ot.opertype,ot.productid,ot.productname,ot.qty,ot.createdate)
VALUES ('{0}','{1}','平行作业工序释放',3,'{2}','{3}','{4}',SYSDATE);
END;";
                OracleHelper.ExecuteSql(string.Format(strSql, dt.Rows[0]["containerid"].ToString(), dt.Rows[0]["containername"].ToString(),
                    dt.Rows[0]["productid"].ToString(), dt.Rows[0]["productname"].ToString(), dt.Rows[0]["qty"].ToString()));
            }
        }

        /// <summary>
        /// 非标移动
        /// add:Wangjh 20220720
        /// </summary>
        /// <param name="strContainerName"></param>
        /// <param name="strWorkFlow"></param>
        /// <param name="strWFVersion"></param>
        /// <param name="strToStep"></param>
        /// <param name="strEmployee"></param>
        /// <param name="strMsg"></param>
        /// <param name="notes"></param>
        /// <returns></returns>
        public Boolean ContainerMoveNonStd(string strContainerName, string strWorkFlow, string strWFVersion, string strToStep, ref string strMsg, string notes = "")
        {
            string strTxnDocName = "", strTxnName = "";
            strTxnDocName = "MoveNonStdDoc";
            strTxnName = "MoveNonStd";

            var m_DataList = new List<ClientAPIEntity>();
            var dataEntity = new ClientAPIEntity();

            dataEntity = new ClientAPIEntity("Container", InputTypeEnum.Details, DataTypeEnum.ContainerField, strContainerName, "");
            m_DataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity("ToWorkflow", InputTypeEnum.Details, DataTypeEnum.RevisionedObjectField, strWorkFlow, strWFVersion);
            m_DataList.Add(dataEntity);
            dataEntity = new ClientAPIEntity("ToStep", InputTypeEnum.Details, DataTypeEnum.NamedSubentityField, strToStep, "");
            m_DataList.Add(dataEntity);
            dataEntity = new ClientAPIEntity("ReportEmployee", InputTypeEnum.Details, DataTypeEnum.NamedObjectField, ConfigurationManager.AppSettings["CamstarUserName"].ToString(), "");
            m_DataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity("Notes", InputTypeEnum.Details, DataTypeEnum.DataField, notes, "");
            m_DataList.Add(dataEntity);

            CamstarClientAPI clientData = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(),
              ConfigurationManager.AppSettings["CamstarPassword"].ToString(), ConfigurationManager.AppSettings["ServerHost"].ToString(), ConfigurationManager.AppSettings["ServerPort"].ToString());

            return clientData.RunTxnService(strTxnDocName, strTxnName, m_DataList, ref strMsg);
        }

        /// <summary>
        /// 标准移动
        /// add:Wangjh 20221125
        /// </summary>
        /// <param name="strContainerName"></param>
        /// <param name="strEmployee"></param>
        /// <param name="notes"></param>
        /// <param name="strMsg"></param>
        /// <returns></returns>
        public Boolean ContainerMoveStd(string strContainerName, string strEmployee, string notes, ref string strMsg)
        {
            string strTxnDocName = "", strTxnName = "";
            strTxnDocName = "MoveStdDoc";
            strTxnName = "MoveStd";

            var m_DataList = new List<ClientAPIEntity>();
            var dataEntity = new ClientAPIEntity();

            dataEntity = new ClientAPIEntity("Container", InputTypeEnum.Details, DataTypeEnum.ContainerField, strContainerName, "");
            m_DataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity("ReportEmployee", InputTypeEnum.Details, DataTypeEnum.NamedObjectField, strEmployee, "");
            m_DataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity("Notes", InputTypeEnum.Details, DataTypeEnum.DataField, notes, "");
            m_DataList.Add(dataEntity);

            CamstarClientAPI clientData = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(),
             ConfigurationManager.AppSettings["CamstarPassword"].ToString(), ConfigurationManager.AppSettings["ServerHost"].ToString(), ConfigurationManager.AppSettings["ServerPort"].ToString());

            return clientData.RunTxnService(strTxnDocName, strTxnName, m_DataList, ref strMsg);

        }

        /// <summary>
        /// 领料流程中,再次回到工艺确认
        /// add:Wangjh 20220720
        /// </summary>
        /// <param name="containerName"></param>
        public void ContainerAgainWFConfirm(string containerName)
        {
            DataTable dt = OracleHelper.Query("SELECT * FROM containercurrentinfo cci WHERE cci.isinstore=-1 AND cci.containername='" + containerName + "'").Tables[0];
            string strMsg = "";
            if (dt.Rows.Count == 0)
            {
                return;
            }

            if (ContainerMoveNonStd(containerName, dt.Rows[0]["workflowname"].ToString(), dt.Rows[0]["workflowrevision"].ToString(), "工艺确认", ref strMsg))
            {
                OracleHelper.ExecuteSql(" update containercurrentinfo cci set cci.techniquedate=null where cci.containername='" + containerName + "' ");
            }
        }

        /// <summary>
        /// 外包报工和检验
        /// add:Wangjh 20221125
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public uMESProcessResult ContainerCommisonReportAndCheck(Dictionary<string, object> para)
        {
            uMESProcessResult re = new uMESProcessResult();
            re.Result = false;
            var resultDt = new DataTable();
            resultDt.Columns.Add("ContainerName");
            resultDt.Columns.Add("IsMove");

            //基础信息查询
            string strSql = @"select cci.workflowstepid custepid,ws.workflowstepid commiStepid,cci.containertype,cci.qty wipqty,cm.* from containercommissioning cm 
left join workflowstep fws on fws.workflowstepid=cm.workflowstepid
left join workflowstep inws on inws.workflowstepid=cm.inworkflowstepid
left join containercurrentinfo cci on cci.containerid=cm.containerid
left join workflowstep ws on ws.workflowid=fws.workflowid and ws.sequence>=fws.sequence and ws.sequence<inws.sequence
where cci.togetherflag='{0}' and ws.workflowstepname='{1}'
and cci.workflowid=fws.workflowid and cm.isuse=0 and cm.indate is null 
order by cm.proposedate desc";
            var baseDt = new DataTable();
            if (string.IsNullOrWhiteSpace(para["SonWorkflowStepName"].ToString()))
            {
                baseDt = OracleHelper.Query(string.Format(strSql, para["ContainerName"], para["WorkflowStepName"])).Tables[0];
            }
            else
            {
                strSql = @"select cci.workflowstepid custepid,ws.workflowstepid commiStepid,cci.containertype,cci.qty wipqty,cm.* from containercommissioning cm 
left join workflowstep fws on fws.workflowstepid=cm.workflowstepid
left join workflowstep inws on inws.workflowstepid=cm.inworkflowstepid
left join containercurrentinfo cci on cci.containerid=cm.containerid
left join workflowstep ws on ws.workflowid=fws.workflowid and ws.sequence>=fws.sequence and ws.sequence<inws.sequence
where cci.togetherflag like '{0}%' and cci.containerno = '{1}' 
and ws.workflowstepname='{2}' and exists (select 1 from containersubcontainer cc where cc.subcontainerid=cci.containerid)
and cci.workflowid=fws.workflowid and cm.isuse=0 and cm.indate is null 
order by cm.proposedate desc";
                baseDt = OracleHelper.Query(string.Format(strSql, para["ProductName"], para["ContainerNo"], para["SonWorkflowStepName"])).Tables[0];
            }
            if (baseDt.Rows.Count == 0)
            {
                re.Message = "未找到批次";
                return re;
            }
            var commiStepid = baseDt.Rows[0]["commiStepid"].ToString();//外委报工工序

            if (OracleHelper.GetSingle(string.Format(@"SELECT 1 FROM containerstepworkreport csw WHERE csw.containerid='{0}' AND csw.workflowstepid='{1}' AND csw.isuse=0",
                baseDt.Rows[0]["containerid"].ToString(), baseDt.Rows[0]["commiStepid"].ToString())) != null)
            {
                re.Message = "已存在报工";
                return re;
            }

            var maxStepId = OracleHelper.Query("SELECT MAX(cm.workflowstepid) maxstepid FROM containercommidetail cm WHERE cm.containercommissioningid = '" + baseDt.Rows[0]["CONTAINERCOMMISSIONINGID"].ToString() + "'").Tables[0].Rows[0]["maxstepid"].ToString();

            var autoReportSql = @"INSERT INTO containerstepworkreport csw (csw.containerstepworkreportid,csw.containerid,csw.workflowstepid,csw.isuse,csw.checktype,csw.workerid,
csw.qty,csw.selfcheckqualifiedqty,csw.selfcheckoutoftoleranceqty,csw.selfchecklossqty,csw.createdate,csw.lossqty) VALUES('{0}','{1}','{2}',0,22,'{3}','{4}','{5}','{6}','{7}',to_date('{8}','yyyy/mm/dd hh24:mi:ss'),'{9}')";
            var autoCheckSql = @"INSERT INTO containercheckinfo cci (cci.containercheckinfoid,cci.containerstepworkreportid,cci.containerid,cci.workflowstepid,cci.checkerid,cci.checkqty,cci.acceptanceqty,cci.acceptanceqty2,cci.defectqty
,cci.reworkqty,cci.lossqty,cci.checktypenote,cci.createdate,cci.isuse) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',1,to_date('{11}','yyyy/mm/dd hh24:mi:ss'),0)";
            var lossSql = @"INSERT INTO CheckQtyChangeRecord(Checkqtychangerecordid,Containercheckinfoid,Containerid,Changeqtytype,Isuse,Qty,Reasonid,Scrapsourcetype,Containerstepworkreportid,Createdate,
Employeeid,Workflowstepid)VALUES('{0}','{1}','{2}',2,0,'{3}','{4}' ,1,'{5}',Sysdate,'{6}','{7}') ";
            var reasonSql = "select * from lossreason ls where ls.description='{0}'";
            var changeConQty = "update container set status='{0}', qty=qty+{1} where containerid='{2}' ";
            var changeConQty2 = "update containercurrentinfo set containerstatus='{0}', qty=qty+{1} where containerid='{2}' ";
            var inCommisonSql = "UPDATE CONTAINERCOMMISSIONING CCG SET CCG.ACCEPTANCEQTY={0},CCG.LOSSQTY={1}, LNAMEJHRNAME='{2}',LNAMEJHRPHONE='{3}',FEVORSHR='{4}',FHDATE=TO_DATE('{5}','yyyy-MM-dd hh24:mi:ss'),ZJFSL='{6}',ccg.outsourcoutno='{7}' where ccg.CONTAINERCOMMISSIONINGID='{8}'";//modify longb 2022-12-13
            var inCommisonDetailSql = "UPDATE containercommidetail cm SET cm.outboundrownum = '{0}' WHERE cm.containercommissioningid = '{1}' AND cm.workflowstepid = '{2}'";

            DataTable childCon = (DataTable)para["ChildItems"];//子卡信息
            var sqlList = new ArrayList();
            var reportId = Guid.NewGuid().ToString();
            var checkId = Guid.NewGuid().ToString();
            if (baseDt.Rows[0]["containertype"].ToString() == "3" || baseDt.Rows[0]["containertype"].ToString() == "2")
            {
                var passQty2 = int.Parse(para["PassQty"].ToString());
                var passQty = int.Parse(para["PassQty"].ToString()) + int.Parse(para["DefectQty"].ToString()) + int.Parse(para["ReworkQty"].ToString());

                sqlList.Add(string.Format(autoReportSql, reportId, baseDt.Rows[0]["containerid"].ToString(), commiStepid, "", para["ReportQty"], 0, 0, 0, para["ReportDate"].ToString(), para["LossQty"]));
                sqlList.Add(string.Format(autoCheckSql, checkId, reportId, baseDt.Rows[0]["containerid"].ToString(), commiStepid, "", para["ReportQty"], passQty, passQty2, para["DefectQty"].ToString(),
                    para["ReworkQty"].ToString(), para["LossQty"].ToString(), para["CheckDate"].ToString()));

                //执行外委调度转入 modify longb 2022-12-13
                sqlList.Add(string.Format(inCommisonSql, passQty, para["LossQty"].ToString(), para["LNAMEJHRNAME"].ToString(), para["LNAMEJHRPHONE"].ToString(), para["FEVORSHR"].ToString(), para["FHDATE"].ToString(), para["ZJFSL"].ToString(), para["OutSourcOutNo"].ToString(), baseDt.Rows[0]["CONTAINERCOMMISSIONINGID"].ToString()));

                //新增出库单行项目号的更新 add by zhangrj 2023-05-30
                sqlList.Add(string.Format(inCommisonDetailSql, para["OutBoundRowNum"].ToString(), baseDt.Rows[0]["CONTAINERCOMMISSIONINGID"].ToString(), commiStepid));

                //处理完后返回的批次
                var reRow = resultDt.NewRow();
                reRow["containername"] = baseDt.Rows[0]["containername"].ToString();
                if (commiStepid == maxStepId)//如果外委序是最大外委序，则不移动
                {
                    reRow["IsMove"] = "0";
                }
                else
                {
                    reRow["IsMove"] = "1";
                }
                resultDt.Rows.Add(reRow);
            }
            if (baseDt.Rows[0]["containertype"].ToString() == "7")
            {//单件单卡
                foreach (DataRow childConRow in childCon.Rows)
                {
                    var _childConRow = baseDt.Select("containername='" + para["ProductName"] + "/" + childConRow["childContainerNo"].ToString() + "'");
                    if (_childConRow.Length > 0)
                    {
                        reportId = Guid.NewGuid().ToString();
                        checkId = Guid.NewGuid().ToString();
                        sqlList.Add(string.Format(autoReportSql, reportId, _childConRow[0]["containerid"].ToString(), commiStepid, "", 1, 0, 0, 0, para["ReportDate"].ToString(), childConRow["LossQty"]));
                        sqlList.Add(string.Format(autoCheckSql, checkId, reportId, _childConRow[0]["containerid"].ToString(), commiStepid, "", 1, 1 - int.Parse(childConRow["LossQty"].ToString()), 1 - int.Parse(childConRow["LossQty"].ToString()), 0,
                            0, childConRow["LossQty"], para["CheckDate"].ToString()));
                        //有报废执行报废
                        if (int.Parse(childConRow["LossQty"].ToString()) > 0)
                        {
                            var _reasonDt = OracleHelper.Query(string.Format(reasonSql, childConRow["LossResonCode"].ToString())).Tables[0];
                            var _resonID = childConRow["LossResonDesc"].ToString();
                            if (_reasonDt.Rows.Count > 0)
                            {
                                _resonID = _reasonDt.Rows[0]["lossreasonid"].ToString();
                            }
                            sqlList.Add(string.Format(lossSql, Guid.NewGuid().ToString(), checkId, _childConRow[0]["containerid"].ToString(), -int.Parse(childConRow["LossQty"].ToString()), _resonID, reportId, "", commiStepid));
                            //关闭并修改批次数量
                            sqlList.Add(string.Format(changeConQty, 2, -1, _childConRow[0]["containerid"].ToString()));
                            sqlList.Add(string.Format(changeConQty2, 2, -1, _childConRow[0]["containerid"].ToString()));
                        }
                        //执行外委调度转入 modify longb 2022-12-13
                        sqlList.Add(string.Format(inCommisonSql, 1 - int.Parse(childConRow["LossQty"].ToString()), childConRow["LossQty"].ToString(), para["LNAMEJHRNAME"].ToString(), para["LNAMEJHRPHONE"].ToString(), para["FEVORSHR"].ToString(), para["FHDATE"].ToString(), para["ZJFSL"].ToString(), para["OutSourcOutNo"].ToString(), childConRow["CONTAINERCOMMISSIONINGID"].ToString()));

                        //新增出库单行项目号的更新 add by zhangrj 2023-05-30
                        sqlList.Add(string.Format(inCommisonDetailSql, para["OutBoundRowNum"].ToString(), childConRow["CONTAINERCOMMISSIONINGID"].ToString(), commiStepid));
                    }
                    var reRow = resultDt.NewRow();
                    reRow["containername"] = _childConRow[0]["containername"].ToString();
                    if (commiStepid == maxStepId) //如果外委序是最大外委序，则不移动
                    {
                        reRow["IsMove"] = "0";//不移动
                    }
                    else
                    {
                        reRow["IsMove"] = "1";
                    }
                    resultDt.Rows.Add(reRow);
                }
            }
            //执行报废
            if (baseDt.Rows[0]["containertype"].ToString() == "2" && int.Parse(para["LossQty"].ToString()) > 0)//批量卡
            {
                var _reasonDt = OracleHelper.Query(string.Format(reasonSql, para["LossResonCode"].ToString())).Tables[0];
                var _resonID = para["LossResonDesc"].ToString();
                if (_reasonDt.Rows.Count > 0)
                {
                    _resonID = _reasonDt.Rows[0]["lossreasonid"].ToString();
                }
                sqlList.Add(string.Format(lossSql, Guid.NewGuid().ToString(), checkId, baseDt.Rows[0]["containerid"].ToString(), -int.Parse(para["LossQty"].ToString()), _resonID, reportId, "", commiStepid));
                //关闭并修改批次数量
                var conStatus = 1;
                if (int.Parse(para["LossQty"].ToString()) >= int.Parse(baseDt.Rows[0]["wipqty"].ToString()))
                {
                    conStatus = 2;
                }
                sqlList.Add(string.Format(changeConQty, conStatus, -1, baseDt.Rows[0]["containerid"].ToString()));
                sqlList.Add(string.Format(changeConQty2, conStatus, -1, baseDt.Rows[0]["containerid"].ToString()));

            }
            if (baseDt.Rows[0]["containertype"].ToString() == "3")//子序号卡
            {
                var mesChildCon = OracleHelper.Query(string.Format("select * from container c where c.parentcontainerid='{0}' and status=1 ",
                    baseDt.Rows[0]["containerid"].ToString())).Tables[0];

                foreach (DataRow childRow in mesChildCon.Rows)
                {
                    sqlList.Add(string.Format(@"INSERT INTO containerstepworkreportchild cswd (cswd.childcontainerid,cswd.containerstepworkreportid) VALUES ('{0}','{1}')",
                        childRow["containerid"].ToString(), reportId));
                }
                var allLossQty = 0; var conStatus = 1;

                foreach (DataRow childConRow in childCon.Rows)
                {
                    var _childConRow = mesChildCon.Select("containername='" + para["ProductName"] + "/" + childConRow["childContainerNo"].ToString() + "'");

                    //有报废执行报废
                    if (_childConRow.Length > 0 && int.Parse(childConRow["LossQty"].ToString()) > 0)
                    {
                        var _reasonDt = OracleHelper.Query(string.Format(reasonSql, childConRow["LossResonCode"].ToString())).Tables[0];
                        var _resonID = childConRow["LossResonDesc"].ToString();
                        if (_reasonDt.Rows.Count > 0)
                        {
                            _resonID = _reasonDt.Rows[0]["lossreasonid"].ToString();
                        }

                        sqlList.Add(string.Format(lossSql, Guid.NewGuid().ToString(), checkId, _childConRow[0]["containerid"].ToString(), -int.Parse(childConRow["LossQty"].ToString()), _resonID, reportId, "", commiStepid));
                        allLossQty++;
                        sqlList.Add(string.Format(changeConQty, 2, -1, _childConRow[0]["containerid"].ToString()));
                    }
                    if (allLossQty > int.Parse(baseDt.Rows[0]["wipqty"].ToString()))
                    {
                        conStatus = 2;
                    }
                }

                sqlList.Add(string.Format(changeConQty, conStatus, -allLossQty, baseDt.Rows[0]["containerid"].ToString()));
                sqlList.Add(string.Format(changeConQty2, conStatus, -allLossQty, baseDt.Rows[0]["containerid"].ToString()));
            }

            OracleHelper.ExecuteSqlTran(sqlList);

            re.DBTable = resultDt;
            re.Result = true;
            return re;
        }

        private const string m_strSuccess = "成功";

        #region 机匣测试服务器连接add:Wangjh 20170925
        /// <summary>
        /// 获取测试机匣服务器Camstar连接地址
        /// </summary>
        /// <returns></returns>
        private string GetJXCamstarConn()
        {
            return ConfigurationManager.AppSettings["JXServerHost"].ToString();
        }
        #endregion

        #region 更新订单状态 add by longb 20221124
        public bool UpdateMfgOrderStatus(Dictionary<string, string> para)
        {
            var updateSql = @"UPDATE MFGORDER m SET m.ORDERSTATUSID=(SELECT o.ORDERSTATUSID FROM ORDERSTATUS o WHERE o.ORDERSTATUSNAME ='{0}'),
                                m.Techconfirm='{1}',m.ISPAUSE='{2}',m.ISDEL='{3}' WHERE m.MFGORDERNAME ='{4}'";
            updateSql = string.Format(updateSql, para["OrderStatus"], para["Techconfirm"], para["IsPaused"], para["IsDel"], para["MfgOrderName"]);
            return OracleHelper.ExecuteSql(updateSql) > 0;
        }
        #endregion

        public void CheckProductFamily(Dictionary<string, string> strList, CamstarClientAPI clientData)
        {
            clientData = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(),
               ConfigurationManager.AppSettings["CamstarPassword"].ToString(), ConfigurationManager.AppSettings["ServerHost"].ToString(), ConfigurationManager.AppSettings["ServerPort"].ToString());
            try
            {
                var productFamily = strList["ProductFamilyName"];
                string resultInfo = string.Empty;
                bool result = false;
                foreach (var pf in productFamily.Split(','))
                {
                    string strSql = string.Format("select count(p.productfamilyid) from ProductFamily p  where p.productfamilyname='{0}'", pf);
                    int cont = Convert.ToInt32(OracleHelper.GetSingle(strSql));
                    if (cont > 0)
                    {
                        continue;
                    }

                    #region  型别
                    List<ClientAPIEntity> dataList = new List<ClientAPIEntity>();
                    ClientAPIEntity dataEntity = new ClientAPIEntity();
                    dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                    dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                    dataEntity.ClientDataName = "Name";
                    dataEntity.ClientDataValue = pf;
                    dataList.Add(dataEntity);
                    result = clientData.CreateModelByStandard("ProductFamilyMaintDoc", "ProductFamilyMaint", "new", dataList, ref resultInfo);
                    LogHelp.WriteLog("ERP订单[" + strList["mfgordername"] + "]新增型别【" + pf + "】" + (result ? "成功" : "失败"));
                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("ERP订单" + strList["mfgordername"] + "新增型别异常" + ex.Message);
            }

                    #endregion
        }
        /// <summary>
        /// 新增设备
        /// </summary>
        /// <param name="equip_code"></param>
        /// <param name="equip_xh"></param>
        /// <param name="factory"></param>
        /// <param name="workcenter"></param>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        public Boolean SaveResourceData(string equip_code, string equip_xh, string factory, string workcenter, ref string strMessage)
        {
            var dataEntityList = new List<ClientAPIEntity>();
            var dataEntity = new ClientAPIEntity();
            //设备编码
            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataName = "Name";
            dataEntity.ClientDataValue = equip_code;
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataEntityList.Add(dataEntity);
            //设备型号
            var ResourceFamilyDT = OracleHelper.Query(string.Format(@"select * from resourcefamily r where r.resourcefamilyname ='{0}'", equip_xh)).Tables[0];
            if (ResourceFamilyDT.Rows.Count > 0)
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataName = "ResourceFamily";
                dataEntity.ClientDataValue = equip_xh;
                dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
                dataEntityList.Add(dataEntity);
            }
            //分厂
            var FactoryDT = OracleHelper.Query(string.Format(@"select * from factory f  where f.factoryname ='{0}'", factory)).Tables[0];
            if (!string.IsNullOrWhiteSpace(factory) && FactoryDT.Rows.Count > 0)
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataName = "Factory";
                dataEntity.ClientDataValue = factory;
                dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
                dataEntityList.Add(dataEntity);
            }
            //工区
            var WorkCenterDT = OracleHelper.Query(string.Format(@"select * from workcenter w where w.workcentername ='{0}'", workcenter)).Tables[0];
            if (!string.IsNullOrWhiteSpace(workcenter) && WorkCenterDT.Rows.Count > 0)
            {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataName = "WorkCenter";
                dataEntity.ClientDataValue = workcenter;
                dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
                dataEntityList.Add(dataEntity);
            }
            CamstarClientAPI clientData;
            clientData = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(),
              ConfigurationManager.AppSettings["CamstarPassword"].ToString(), ConfigurationManager.AppSettings["ServerHost"].ToString(), ConfigurationManager.AppSettings["ServerPort"].ToString());
            var result = clientData.CreateModelByStandard("resourceMaintDoc", "resourceMaint", "New", dataEntityList, ref strMessage);
            return result;
        }
    }
}